var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var orderModel = require('../../models/order/order_list');


mongoose.connect('mongodb://127.0.0.1:27017/rea_db');

//用来监听数据库是否连接成功（还有其他的监听方法，比如disconnected,error）
mongoose.connection.on('connected', function () {
    console.log('rea_db connected');
});

//定义路由，当访问该路由的时候，去数据库查找信息并返回
router.get('/', function (req, res, next) {
    orderModel.find({}, function (err, docs) {
        if (!err) {
            // 转换时间格式
            for (let i = 0; i < docs.length; i++) {
                let date = new Date(docs[i].publish_time)
                docs[i].publish_time = date.format('yyyy-MM-dd')
            }

            // 分类返回，返回报文为二位数组
            var type_0 = [], type_1 = [], type_2 = []
            docs.forEach((order) => {
                if (order.type === 0) type_0.push(order)
                else if (order.type === 1) type_1.push(order)
                else type_2.push(order)
            })
            res.json({ data: [type_0, type_1, type_2], msg: '返回成功！', code: 200 })
        }
    })
})

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份 
        "d+": this.getDate(),                    //日 
        "h+": this.getHours(),                   //小时 
        "m+": this.getMinutes(),                 //分 
        "s+": this.getSeconds(),                 //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds()             //毫秒 
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

module.exports = router;
